﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using LastoRevival.Service.Contracts;
using LastoRevival.Service.Implementations.Exceptions;
using LastoRevival.Service.Contracts.Models;
using LastoRevival.Service.Implementations.Data;

namespace LastoRevival.Service.Implementations
{
	public class ForumService : ServiceBase, IForumService
	{
		private IDataProvider DataProvider
		{
			get
			{
				return DependencyFactory.GetDataProvider();
			}
		}

		UserService userService;

		public ForumService(UserService userService)
		{
			this.userService = userService;
		}


		public IEnumerable<PreviewForumModel> GetVisibleForums(Guid loginToken)
		{
			UpdateSession(loginToken);

			var profile = userService.GetActiveProfile(loginToken);

			if (profile.Details.IsAdministrator)
			{
				return DataProvider.GetAllForums();
			}
			else
			{
				return DataProvider.GetVisibleForums(profile.Details.GroupID);
			}

		}


		public ViewForumModel GetForumAndThreads(Guid loginToken, int forumID, int currentPage, int pageSize)
		{
			UpdateSession(loginToken);

			var profile = userService.GetActiveProfile(loginToken);

			if (!profile.CanViewForum(forumID))
			{
				throw new NoAccessException();
			}

			var details = DataProvider.GetForum(forumID);
			var threads = DataProvider.GetThreadsOnPage(forumID, currentPage, pageSize);
			var canCreate = profile.CanCreateThread(forumID);

			return new ViewForumModel { ForumDetails = details, Threads = threads, CanCreateThread = canCreate };
		}


		public PreviewForumModel GetForum(Guid loginToken, int forumID)
		{
			UpdateSession(loginToken);

			var profile = userService.GetActiveProfile(loginToken);

			if (!profile.CanViewForum(forumID))
			{
				throw new NoAccessException();
			}

			return DataProvider.GetForum(forumID);
		}
	}
}
